package cn.basic.common.filter;

import cn.basic.org.dto.DepartmentDTO;
import cn.basic.utils.BodyRequestWrapper;
import cn.basic.utils.SnowFlakeUtil;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @description: BaseFilter
 * @date: 2023/3/11 14:54
 * @author: ZhaoLc
 * @version: 1.0
 */
public class BaseFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取request的body参数
        try {
            String postContent = getBody(request);
            // 字符串转json
            Long snowFlakeId = SnowFlakeUtil.getSnowFlakeId();

            JSONObject jsStr = JSONObject.parseObject(postContent);
            jsStr.put("batchId",snowFlakeId);
            postContent = jsStr.toJSONString();
            //将参数放入重写的方法中
            request = new BodyRequestWrapper(request, postContent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        filterChain.doFilter(request, servletResponse);
    }

    //获取Request的body数据
    private String getBody(ServletRequest request) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {

        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringBuilder.toString();
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
